package com.wxg.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.wxg.common.core.dto.Address;
import com.wxg.config.SysLog;
import com.wxg.service.DictService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.*;

/**
 * Created by void on 2019/11/7.
 */
@Slf4j
@RequestMapping("/fastjson/test")
@RestController
public class FastJsonController {

    @Autowired
    private DictService dictService;

    @GetMapping("/validDefaultValue")
    public Address validDefaultValue(){
        Address address = new Address();
        address.setPhone("11111111111");
        address.setCreateTime(new Date());
        address.setNow(LocalDateTime.now());

        this.test1(address);

        return address;
    }

    /**
     * 子方法的return并不会影响上层调用结果
     * @param address
     */
    private void test1(Address address){
        if(StringUtils.isNotBlank(address.getPhone())){
            log.info("1111111111");
            return;
        }else{
            log.info("22222222222");
        }
        log.info("3333333333333333");
        return;
    }

    /**
     * @link FastJsonConfiguration
     * @return
     */
    @GetMapping("/ref")
    public Object ref(){
        //在没有配置fastjson去除序列化引用时会打印成
        //{"obj":{"addressId":"","createTime":1573140973603,"defaultFlag":false,"phone":"11111111111","province":"","updateTime":""},"list":[{"$ref":"$.obj"}]}

        List<Address> list = new ArrayList<>();
        Address address = new Address();
        address.setPhone("11111111111");
        address.setCreateTime(new Date());
        list.add(address);

        Map<String, Object> map = new HashMap<>();
        map.put("obj", list.get(0));
        map.put("list", list);
        return map;
    }

    /**
     * 序列化带分页时丢失了null的字段
     * @return
     */
    @GetMapping("/fieldLost")
    public Map<String, Object> fieldLost(){
        Map<String, Object> map = new HashMap<>();
        PageInfo pageInfo = dictService.queryAll();
        map.put("list", pageInfo);
        map.put("obj", pageInfo.getList().get(0));
        return map;
    }

    @GetMapping("/jsonObject")
    public JSONObject jsonObject(){
        JSONObject obj = new JSONObject();
        obj.put("name", "wxg");
        obj.put("age", 23);
        obj.put("address", null);
        obj.put("sex", "");
        return obj;
    }

    @SysLog(value = "测试")
    @GetMapping("/map")
    public Map map(){
        Map<String, Object> map = new HashMap<>();
        map.put(null, "123");
        map.put("wxg", null);
        return map;
    }
}
